# coding: utf-8

from django.http import Http404
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.authentication import BasicAuthentication
from api_wxapp.auth import WXAppTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from me.exceptions import *
from rest_framework import serializers


def success_resp(data={}):
    return Response({
        'code': 0,
        'data': data
    }, status.HTTP_200_OK)


def error_resp(code):
    return Response({
        'code': 0,
        'data': ERROR_CODES.get(code, '未知异常')
    }, status.HTTP_200_OK)


class JSONSerializerField(serializers.Field):
    """ Serializer for JSONField -- required to make field writable"""
    def to_internal_value(self, data):
        return data

    def to_representation(self, value):
        return value


class WXAppAPIView(APIView):
    model = None
    authentication_classes = (WXAppTokenAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated, )

    def has_obj_permission(self, request, obj):
        assert_and_exception(request.user, obj.user, 1002)

    def get_object(self, id):
        return None

    def check_obj_and_owner_permission(self, request, model=None, id=None):
        if model:
            ins = get_object_or_404(model, id)
        else:
            ins = get_object_or_404(self.model, id)
        self.has_obj_permission(request, ins)
        return ins